 //
//  BKFirstPageNewsListViewController.m
//  bestkeep
//
//  Created by utouu666 on 17/2/16.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BKFirstPageNewsListViewController.h"
#import "BKMain_ClassifyKindsHeaderView.h"
#import "BKMainCommon.h"
#import "BKmain_CellModel.h"
#import "BKMain_SectionModel.h"
#import "BKMain_ClassifyViewCell.h"
#import "BKMain_thwartwiseGoodsCell.h"
#import "BKMain_PrivilegeCollectionCell.h"
#import "BKMain_CustomSwitchBtn.h"
#import "BKMain_SingleCollectionViewCell.h"
@interface BKFirstPageNewsListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) NSArray *categoryIdArray;
@property(nonatomic,strong)UICollectionView *myCollectionView;
@property(nonatomic,assign)NSInteger index;
@property(nonatomic,strong)NSMutableArray<BKMain_SectionModel*>*dataArray;
@property(nonatomic,strong)NSString *type;
@property(nonatomic,strong)NSString *categoryId;
@property(nonatomic,assign)NSInteger currentPage;
@property(nonatomic,strong)NSString *filterTerms;
@property(nonatomic,strong)NSString *order_key;
@property(nonatomic,strong)NSString *sort_name;
@property(nonatomic,assign)NSInteger totalPage;
@property(nonatomic,assign) NSTimeInterval timeInterval;
@property(nonatomic,assign)BOOL isRest;
@property(nonatomic,strong)ExceptionView *exceptionView;
@property (nonatomic,strong) UIImageView *backToTop;
@property(nonatomic,assign)BOOL isShowNoData;
//@property(nonatomic,assign) BKMain_GoodsListTableShowType goodsShowType;

//@property(nonatomic,strong)NSMutableArray *classifyData_Array;
@end

@implementation BKFirstPageNewsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void)passCategoryIdArray:(id)data{
    
    _categoryIdArray = data;
}

-(void)zj_viewDidLoadForIndex:(NSInteger)index{
    
    [self initializeParamWithIndex:index];
    self.index = index;
    [self initializeComponent];
    self.isRest = YES;
    self.isShowNoData = NO;
    
}
-(void)zj_viewWillAppearForIndex:(NSInteger)index{
    if (self.isRest == YES) {
        
    }else{
        self.isRest = NO;
    }
    self.index = index;
    
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",(long)self.index],@"index",self.sort_name,@"sort_name",self.order_key,@"order_key", nil];
    if (self.isRest) {
        [infoDic setObject:@"0" forKey:@"isRest"];
    }else{
        [infoDic setObject:@"1" forKey:@"isRest"];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"isRestNotification" object:@"isRest" userInfo:infoDic];
    
    
    
    
}
-(void)viewDidAppear:(BOOL)animated{
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(only_changeType:) name:@"only_changeTypeNotication" object:@"goodsShowType"];
}
-(void)viewDidDisappear:(BOOL)animated{
    [self.myCollectionView.mj_footer endRefreshing];
    [self.myCollectionView.mj_header endRefreshing];
    [BKIndicationView dismiss];
}

-(void)initializeComponent{
    self.view.backgroundColor = [UIColor whiteColor];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    if (self.index < 3) {
        _myCollectionView.frame = self.view.frame;
        _myCollectionView.backgroundColor = [UIColor whiteColor];
    }else{
        _myCollectionView.frame = CGRectMake(0, 35, SCREENWIDTH, self.view.frame.size.height - 35);
        _myCollectionView.backgroundColor = RGB(242, 242, 242);
    }
    
    _myCollectionView.delegate = self;
    _myCollectionView.dataSource = self;
    _myCollectionView.showsVerticalScrollIndicator = NO;
    _myCollectionView.showsHorizontalScrollIndicator = NO;
    [_myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerID"];
    [_myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerID"];
    [self.view addSubview:_myCollectionView];
    self.currentPage = 1;
    [self checkNetWorking];
    [self setRefresh];
    
    _backToTop = [[UIImageView alloc] init];
    _backToTop.image = [UIImage imageNamed:@"BKMain_backToTop"];
    _backToTop.userInteractionEnabled = YES;
    _backToTop.hidden = YES;
    UITapGestureRecognizer *backTop = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backTop)];
    [_backToTop addGestureRecognizer:backTop];
    [self.view addSubview:_backToTop];
    [_backToTop mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).offset(-12);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-12);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(30);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetWorking) name:RequestManagerReachabilityDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestClassifyDataWithPrice:) name:@"priceNotication" object:@"priceType"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestClassifyDataWithType:) name:@"typeNotication" object:@"classifyType"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshFirstPage) name:@"refreshFirstPageData" object:nil];
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeType:) name:@"changeTypeNotication" object:@"goodsShowType"];
    
}

//返回顶部
-(void)backTop{
    _backToTop.hidden = YES;
    [_myCollectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}
-(void)refreshFirstPage{
    if (self.timeInterval) {
        if ([self computeTimeintervalWithTimeInterval:self.timeInterval]) {
            if (self.myCollectionView.mj_header.state == MJRefreshStateIdle) {
                [self.myCollectionView.mj_header beginRefreshing];
                NSDate *nowDate = [NSDate date];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                dateFormatter.dateFormat = @"yyy-MM-dd HH:mm:ss";
                self.timeInterval = [nowDate timeIntervalSince1970];
            }
            
        }
        
        
    }else{
        if (self.myCollectionView.mj_header.state == MJRefreshStateIdle) {
            [self.myCollectionView.mj_header beginRefreshing];
            NSDate *nowDate = [NSDate date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
            dateFormatter.dateFormat = @"yyy-MM-dd HH:mm:ss";
            self.timeInterval = [nowDate timeIntervalSince1970];
        }
        
        
    }
    
}
//计算距离上次点击的时间差
-(BOOL)computeTimeintervalWithTimeInterval:(NSTimeInterval)lastTimeInterval{
    
    //设置间隔时间
    int interval = 2.5;
    //获取当前时间
    NSDate *nowDate = [NSDate date];
    //创建时间格式
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    dateFormatter.dateFormat = @"yyy-MM-dd HH:mm:ss";
    //现在时间戳
    NSTimeInterval now = [nowDate timeIntervalSince1970];
    //间隔----
    NSTimeInterval value = now - lastTimeInterval;
    
    NSString *secondStr = [NSString stringWithFormat:@"%.2f",value];
    
    CGFloat second = [secondStr floatValue];//秒
    NSLog(@"间隔------%f秒",second);
    if (second >= interval) {
        return YES;
    }else{
        return NO;
    }
    
    
}

-(void)checkNetWorking{
    
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            [self requestListData];
        }
            break;
            
        default: {
            [[[BKAnimatedAlert alloc]init] BKAlert_Style:BKAlertStyle_NoSave detail:@"请检查您的网络"];
            [self.myCollectionView.mj_header endRefreshing];
            [self.myCollectionView.mj_footer endRefreshing];
            BKFirstPageDataModel *FPData;
            NSDictionary *FPData_dic;
            switch (self.index) {
                case 0:
                    FPData = [BKFirstPageDataModel getCurrentFPData:FPData_firstType];
                    FPData_dic= [self dicWithData:FPData.FPData_first];
                    if (FPData_dic.allKeys != 0) {
                        [self bindFirstPageData:FPData_dic];
                    }
                    break;
                case 1:
                    if (self.currentPage == 1) {
                        FPData = [BKFirstPageDataModel getCurrentFPData:FPData_secondType_1];
                        FPData_dic = [self dicWithData:FPData.FPData_second_1];
                        if (FPData_dic.allKeys != 0) {
                            [self bindFirstPageData:FPData_dic];
                        }
                        
                    }
                    
                    break;
                case 2:
                    if (self.currentPage == 1) {
                        FPData = [BKFirstPageDataModel getCurrentFPData:FPData_secondType_2];
                        FPData_dic = [self dicWithData:FPData.FPData_second_2];
                        if (FPData_dic.allKeys != 0) {
                            [self bindFirstPageData:FPData_dic];
                        }
                        
                    }
                    break;
                default:
                    if (self.currentPage == 1) {
                        FPData = [BKFirstPageDataModel getCurrentFPData:FPData_thirdType];
                        FPData_dic = [self dicWithData:FPData.FPData_third];
                        if (FPData_dic.allKeys != 0) {
                            [self bindRecommendData:[FPData_dic objectForKey:self.categoryId]];
                        }
                        
                    }
                    
                    break;
            }
            return;
            
            
            break;
        }
    }
}
-(void)requestClassifyDataWithType:(NSNotification *)sender{
    NSString *str = sender.userInfo[@"index"];
    if ([str integerValue] == self.index) {
        NSDictionary *dic = sender.userInfo;
        self.currentPage = [dic[@"currentPage"] integerValue];
        self.order_key = dic[@"order_key"];
        self.sort_name = dic[@"sort_name"];
        [self.myCollectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        if (self.index > 2) {
            self.isShowNoData = NO;
            _myCollectionView.mj_footer = nil;
            MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateMore)];
            footer.stateLabel.textColor = LoadMoreDataTitleColor;
            footer.stateLabel.font = [UIFont systemFontOfSize:14];
            footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
            UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
            loadingView.hidesWhenStopped = YES;
            loadingView.color = IndictorViewColor;
            [footer addSubview:loadingView];
            _myCollectionView.mj_footer = footer;
            _myCollectionView.mj_footer.automaticallyHidden = YES;
        }

        [self checkNetWorking];
    }
    
}
-(void)requestClassifyDataWithPrice:(NSNotification *)sender{
    NSString *str = sender.userInfo[@"index"];
    if ([str integerValue] == self.index){
        NSDictionary *dic = sender.userInfo;
        self.currentPage = [dic[@"currentPage"] integerValue];
        self.order_key = dic[@"order_key"];
        self.sort_name = dic[@"sort_name"];
        [self.myCollectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        if (self.index > 2) {
            self.isShowNoData = NO;
            _myCollectionView.mj_footer = nil;
            MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateMore)];
            footer.stateLabel.textColor = LoadMoreDataTitleColor;
            footer.stateLabel.font = [UIFont systemFontOfSize:14];
            footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
            UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
            loadingView.hidesWhenStopped = YES;
            loadingView.color = IndictorViewColor;
            [footer addSubview:loadingView];
            _myCollectionView.mj_footer = footer;
            _myCollectionView.mj_footer.automaticallyHidden = YES;
        }

        [self checkNetWorking];
        
    }
    
}
#pragma mark -------------UIScrollViewDelegate-----------------------
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    _backToTop.hidden = (scrollView.contentOffset.y > IPHONE_HEIGHT * 0.5) ? NO : YES;
}
#pragma mark -------------collectionViewDelegate-------------------
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if(_dataArray){
        return _dataArray.count;
    }
    return 0;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    BKMain_SectionModel *s = _dataArray[section];
    if(s.cells) {
        return s.cells.count;
    }
    return 0;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count != 0) {
        BKMain_SectionModel *s = _dataArray[indexPath.section];
        BKmain_CellModel *item = s.cells[indexPath.row];
        
        
        if ([item.className isEqualToString:NSStringFromClass([BKMain_RecommendCell class])]) {
            BKMain_RecommendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:item.reuseIdentifier forIndexPath:indexPath];
            if (indexPath.row == 2) {
                cell.lineView.hidden = YES;
            }else{
                cell.lineView.hidden = NO;
            }
            SEL selector = NSSelectorFromString(@"fillData:");
            if([cell respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
                [cell performSelector:selector withObject:item.userInfo];
#pragma clang diagnostic pop
            }
            
            return cell;
        }else{
            UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:item.reuseIdentifier forIndexPath:indexPath];
            SEL selector = NSSelectorFromString(@"fillData:");
            if([cell respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
                [cell performSelector:selector withObject:item.userInfo];
#pragma clang diagnostic pop
            }
            
            return cell;
        }
        
    }
    return nil;
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    BKMain_SectionModel *s = _dataArray[indexPath.section];
    BKmain_CellModel *item = s.cells[indexPath.row];
    return item.size;
    
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
    
    
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
    
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *view = nil;
    
    if (kind == UICollectionElementKindSectionFooter) {
        view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerID" forIndexPath:indexPath];
        view.backgroundColor = RGB(242, 242, 242);
        
        
        if ((self.index == 0 && (indexPath.section == self.dataArray.count - 1)) ||(self.index >0 && (self.isShowNoData == YES))) {
            UIImageView *noData = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 46)];
            noData.image = [UIImage imageNamed:@"BKMain_NoData"];
            [view addSubview:noData];
            
        }
        
    }else{
        view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerID" forIndexPath:indexPath];
        view.backgroundColor = RGB(242, 242, 242);
    }
    
    return view;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (self.index > 0) {
        return CGSizeMake(SCREENWIDTH, 0);
    }
    BKMain_SectionModel *s = _dataArray[section];
    
    
    if (s.cells.count > 0) {
        BKmain_CellModel *item = s.cells[0];
        return CGSizeMake(SCREENWIDTH, ([item.className isEqualToString:@"BKMain_GoodsTitleCell"] || [item.className isEqualToString:@"BKMain_ActiveCel"] || [item.className isEqualToString:@"BKMain_ClassifyTitleCell"]||[item.className isEqualToString:@"BKMain_TitleCell"] || [item.className isEqualToString:@"BKMain_SimplePicCell"])  ? 5 : 0.1);
        
    }else{
        
        return CGSizeMake(SCREENWIDTH, 0);
    }
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    BKMain_SectionModel *s = _dataArray[section];
    if (self.index <= 0) {
        if (section == self.dataArray.count - 1) {
            return CGSizeMake(SCREENWIDTH, 46);
        }else{
            return CGSizeMake(SCREENWIDTH, 0);
        }
        
    }else if (self.index < 3){
        if (section != self.dataArray.count -1) {
            if (s.cells.count > 0) {
                BKmain_CellModel *item = s.cells[0];
                return CGSizeMake(SCREENWIDTH, ([item.className isEqualToString:@"BKMain_GoodsTitleCell"]  || [item.className isEqualToString:@"BKMain_ClassifyTitleCell"]|| [item.className isEqualToString:@"BKMain_CycleScrollViewCell"])  ? 5 : 0.1);
                
            }else{
                return CGSizeMake(SCREENWIDTH, 0);
                
            }
            
        }else if (self.isShowNoData == YES){
            return CGSizeMake(SCREENWIDTH, 46);
        }else{
            return CGSizeMake(SCREENWIDTH, 0);
        }
        
    }else{
        if (section != self.dataArray.count - 1) {
            return CGSizeMake(SCREENWIDTH, 0);
        }else if (self.isShowNoData == YES){
            return CGSizeMake(SCREENWIDTH, 46);
        }else{
            return CGSizeMake(SCREENWIDTH, 0);
        }
        
    }
    return CGSizeMake(SCREENWIDTH, 0);
}
#pragma mark -------------------------设置刷新---------------------------------
-(void)setRefresh{
    MJRefreshGifHeader *headerRefresh = [BKRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    self.myCollectionView.mj_header = headerRefresh;
    
    
    if (self.index > 0) {
        self.isShowNoData = NO;
        MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateMore)];
        footer.stateLabel.textColor = LoadMoreDataTitleColor;
        footer.stateLabel.font = [UIFont systemFontOfSize:14];
        footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
        UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
        loadingView.hidesWhenStopped = YES;
        loadingView.color = IndictorViewColor;
        [footer addSubview:loadingView];
        _myCollectionView.mj_footer = footer;
        _myCollectionView.mj_footer.automaticallyHidden = YES;
    }
    
    
}
-(void)refreshData{
    self.currentPage = 1;
    self.isShowNoData = NO;
    
    if (self.index > 0) {
        self.myCollectionView.mj_footer = nil;
        self.isShowNoData = NO;
        MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateMore)];
        footer.stateLabel.textColor = LoadMoreDataTitleColor;
        footer.stateLabel.font = [UIFont systemFontOfSize:14];
        footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
        UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
        loadingView.hidesWhenStopped = YES;
        loadingView.color = IndictorViewColor;
        [footer addSubview:loadingView];
        _myCollectionView.mj_footer = footer;
        _myCollectionView.mj_footer.automaticallyHidden = YES;
    }
    
    
    [self checkNetWorking];
}
-(void)updateMore{
    if ([BKMainCommon checkNetWork] == NO) {
        [self.myCollectionView.mj_header endRefreshing];
        [self.myCollectionView.mj_footer endRefreshing];
        return;
    }
    
    if (self.totalPage > 0) {
        
        if (self.currentPage < self.totalPage) {
            self.currentPage = self.currentPage +1;
            if (self.index == 1 || self.index == 2) {
                [self requestRecommendData];
            }else if (self.index >2){
                [self requestClassifyData];
            }
        }else{
            if (self.currentPage == self.totalPage) {
                self.isShowNoData = YES;
            }else{
                self.isShowNoData = NO;
            }
            
            [self.myCollectionView.mj_header endRefreshing];
            self.myCollectionView.mj_footer = nil;
        }
        
    }else{
        [self.myCollectionView.mj_header endRefreshing];
        [self.myCollectionView.mj_footer endRefreshing];
        
    }
    
}
#pragma mark -------------------------请求数据---------------------------------

//根据下标初始化参数
-(void)initializeParamWithIndex:(NSInteger)index{
    switch (index) {
        case 0:
            self.type = @"0";
            self.categoryId = @"0";
            self.currentPage = -1;
            self.filterTerms = @"-1";
            self.order_key = @"";
            self.sort_name = @"";
            break;
        case 1:
            self.type = @"1";
            self.categoryId = @"1";
            self.currentPage = -1;
            self.filterTerms = @"-1";
            self.order_key = @"";
            self.sort_name = @"";
            break;
        case 2:
            self.type = @"2";
            self.categoryId = @"2";
            self.currentPage = -1;
            self.filterTerms = @"-1";
            self.order_key = @"";
            self.sort_name = @"";
            break;
        default:
            self.type = @"3";
            self.categoryId = self.categoryIdArray[index];
            self.currentPage = -1;
            self.filterTerms = @"-1";
            self.order_key = @"";
            self.sort_name = @"";
            break;
    }
}
//创建请求参数
-(NSDictionary *)creatRequestParamWithType:(NSString *)type categoryId:(NSString *)categoryId currentPage:(NSInteger)currentPage filterTerms:(NSString *)filterTerms order_key:(NSString *)order_key sort_name:(NSString *)sort_name{
    NSString *currentPageStr;
    if (currentPage == -1) {
        currentPageStr = @"1";
    }else{
        currentPageStr = [NSString stringWithFormat:@"%ld",(long)currentPage];
    }
    NSDictionary *paramDic = [[NSDictionary alloc]init];
    paramDic = @{@"type":[NSString stringWithFormat:@"%@",type],
                 @"id":[NSString stringWithFormat:@"%@",categoryId],
                 @"currentPage":currentPageStr,
                 @"filterTerms":[NSString stringWithFormat:@"%@",filterTerms],
                 @"order_key":[NSString stringWithFormat:@"%@",order_key],
                 @"sort_name":[NSString stringWithFormat:@"%@",sort_name]
                 };
    return paramDic;
}
//请求数据
-(void)requestListData{
    
//    __weak typeof(self) weakSelf = self;
//    
//    __strong typeof(weakSelf) strongSelf = weakSelf;
    
    if(self.exceptionView) {
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    
    if (self.currentPage == self.totalPage) {
        self.isShowNoData = YES;
    }else{
        self.isShowNoData = NO;
    }
    
    if (self.index>2) {
        
        [self requestClassifyData];
    }else{
        [BKIndicationView showInView:self.view Point:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
        NSDictionary *paramDic = [self creatRequestParamWithType:self.type categoryId:self.categoryId currentPage:self.currentPage filterTerms:self.filterTerms order_key:self.order_key sort_name:self.sort_name];
        
        __weak typeof(self) weakSelf = self;
        
        [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"/index_v300"] parameters:paramDic success:^(id  _Nullable responseObject) {
            
            __strong typeof(weakSelf) strongSelf = weakSelf;
            
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                if (success) {
                    NSDictionary *data_dic = responseObject[@"data"];
                    
                    if(!data_dic || data_dic.count == 0) {
                        return;
                    }
                    
                    [strongSelf.dataArray removeAllObjects];
                    [strongSelf bindFirstPageData:data_dic];
                    [strongSelf.myCollectionView.mj_header endRefreshing];
                    if (strongSelf.index >=1 && [BKMainCommon checkNetWork] == YES) {
                        [strongSelf requestRecommendData];
                    }
                    NSData *data = [strongSelf returnDataWithDictionary:responseObject[@"data"]];
                    BKFirstPageDataModel *dataModel;
                    if (strongSelf.index == 0) {
                        dataModel = [BKFirstPageDataModel getCurrentFPData:FPData_firstType];
                        [dataModel.realm beginWriteTransaction];
                        dataModel.FPData_first = data;
                    }
                    if (strongSelf.index == 1) {
                        dataModel = [BKFirstPageDataModel getCurrentFPData:FPData_secondType_1];
                        [dataModel.realm beginWriteTransaction];
                        dataModel.FPData_second_1 = data;
                    }
                    if (strongSelf.index == 2) {
                        dataModel = [BKFirstPageDataModel getCurrentFPData:FPData_secondType_2];
                        [dataModel.realm beginWriteTransaction];
                        dataModel.FPData_second_2 = data;
                    }
                    
                    [dataModel.realm commitWriteTransaction];
                    
                    
                    
                }else{
                    BKFirstPageDataModel *FPData;
                    NSDictionary *FPData_dic;
                    switch (strongSelf.index) {
                        case 0:
                            FPData = [BKFirstPageDataModel getCurrentFPData:FPData_firstType];
                            FPData_dic= [strongSelf dicWithData:FPData.FPData_first];
                            if (FPData_dic.allKeys != 0) {
                                [strongSelf bindFirstPageData:FPData_dic];
                            }else{
                                [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
                                [strongSelf setUpErrorUIWith:502];
                            }
                            break;
                        case 1:
                            FPData = [BKFirstPageDataModel getCurrentFPData:FPData_secondType_1];
                            FPData_dic = [strongSelf dicWithData:FPData.FPData_second_1];
                            if (FPData_dic.allKeys != 0) {
                                [strongSelf bindFirstPageData:FPData_dic];
                            }else{
                                [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
                                [strongSelf setUpErrorUIWith:502];
                            }
                            break;
                        case 2:
                            FPData = [BKFirstPageDataModel getCurrentFPData:FPData_secondType_2];
                            FPData_dic = [strongSelf dicWithData:FPData.FPData_second_2];
                            if (FPData_dic.allKeys != 0) {
                                [strongSelf bindFirstPageData:FPData_dic];
                            }else{
                                [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
                                [strongSelf setUpErrorUIWith:502];
                            }
                            break;
                        default:
                            
                            break;
                    }
      
                    [strongSelf.myCollectionView.mj_header endRefreshing];
                    
                    
                    
                    
                }
            }
        } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
            
            if (error && !weakSelf.exceptionView) {
                BKFirstPageDataModel *FPData;
                NSDictionary *FPData_dic;
                switch (self.index) {
                    case 0:
                        FPData = [BKFirstPageDataModel getCurrentFPData:FPData_firstType];
                        FPData_dic= [self dicWithData:FPData.FPData_first];
                        if (FPData_dic.allKeys != 0) {
                            [self bindFirstPageData:FPData_dic];
                        }else{
                            [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
                            [self setUpErrorUIWith:error.code];
                        }
                        break;
                    case 1:
                        FPData = [BKFirstPageDataModel getCurrentFPData:FPData_secondType_1];
                        FPData_dic = [self dicWithData:FPData.FPData_second_1];
                        if (FPData_dic.allKeys != 0) {
                            [self bindFirstPageData:FPData_dic];
                        }else{
                            [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
                            [self setUpErrorUIWith:error.code];
                        }
                        break;
                    case 2:
                        FPData = [BKFirstPageDataModel getCurrentFPData:FPData_secondType_2];
                        FPData_dic = [self dicWithData:FPData.FPData_second_2];
                        if (FPData_dic.allKeys != 0) {
                            [self bindFirstPageData:FPData_dic];
                        }else{
                            [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
                            [self setUpErrorUIWith:error.code];
                        }
                        break;
                    default:
                        
                        break;
                }
                [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
                [self.myCollectionView.mj_header endRefreshing];
                [self.myCollectionView.mj_footer endRefreshing];
                
            }
            
        }];
        
    }
    
    
}
-(void)bindFirstPageData:(NSDictionary *)data{
    if (!data) {
        return;
    }
    _dataArray = [[NSMutableArray alloc]init];
    if (self.myCollectionView.mj_header.isRefreshing) {
        [self.myCollectionView.mj_header endRefreshing];
    }
    
    

    
    NSArray *bannerArray = [data objectForKey:@"bannerList"];
    if (bannerArray.count != 0) {
        BKmain_CellModel *BannerModel = [self creatCellModel:[BKMain_CycleScrollViewCell class] userInfo:[NSDictionary dictionaryWithObjectsAndKeys:bannerArray,@"data",@"1",@"type", nil]size:[BKMain_CycleScrollViewCell calculateSize:bannerArray]];
        BKMain_SectionModel *section0 = [self createSectionModel:@[BannerModel] headerHeight:0 footerHeight:0];
        [self.dataArray addObject:section0];
    }
    NSArray *middleBannerList = [data objectForKey:@"middleBannerList"];
    if (middleBannerList.count != 0) {
        BKmain_CellModel *ActionModel =  [self creatCellModel:[BKMain_ActiveCell class] userInfo:[NSDictionary dictionaryWithObjectsAndKeys:middleBannerList,@"data",@"2",@"type", nil] size:[BKMain_ActiveCell calculateSize:[data objectForKey:@"middleBannerList"]]];
        BKMain_SectionModel *section0 = [self createSectionModel:@[ActionModel] headerHeight:0 footerHeight:0];
        [self.dataArray addObject:section0];
    }
    
    if (self.index == 0) {
        BKmain_CellModel *privilegeModel =  [self creatCellModel:[BKMain_PrivilegeCollectionCell class] userInfo:nil size:[BKMain_PrivilegeCollectionCell calculateSize:nil]];
        BKMain_SectionModel *section1 = [self createSectionModel:@[privilegeModel] headerHeight:0 footerHeight:0];
        [self.dataArray addObject:section1];
    }
    
    
    NSArray *starArray = [data objectForKey:@"startList"];
    if (starArray.count != 0) {
        BKmain_CellModel *hotTitleModel = [self creatCellModel:[BKMain_GoodsTitleCell class] userInfo:HotTitle size:[BKMain_GoodsTitleCell calculateSize:starArray]];
        BKmain_CellModel *hotModel = [self creatCellModel:[BKMain_thwartwiseGoodsCell class] userInfo:starArray size:[BKMain_thwartwiseGoodsCell calculateSize:starArray]];
        BKMain_SectionModel *section2 = [self createSectionModel:@[hotTitleModel,hotModel] headerHeight:0 footerHeight:10];
        [_dataArray addObject:section2];
        
    }
    NSArray *newArray = [data objectForKey:@"newList"];
    if (newArray.count != 0) {
        BKmain_CellModel *newTitleModel = [self creatCellModel:[BKMain_GoodsTitleCell class] userInfo:NewerTitle size:[BKMain_GoodsTitleCell calculateSize:newArray]];
        BKmain_CellModel *newModel = [self creatCellModel:[BKMain_thwartwiseGoodsCell class] userInfo:newArray size:[BKMain_thwartwiseGoodsCell calculateSize:newArray]];
        BKMain_SectionModel *section2 = [self createSectionModel:@[newTitleModel,newModel] headerHeight:0 footerHeight:10];
        [_dataArray addObject:section2];
        
    }
    
    NSArray *jxArray = [data objectForKey:@"bkjxList"];
    NSMutableArray *wellArray = [NSMutableArray array];
    NSMutableArray *wellItemArray = [NSMutableArray array];
    CGFloat h = (SCREENWIDTH < 375) ? (90*SCREENWIDTH/375.f + 10) : (90*SCREENWIDTH/375.f);
    BKmain_CellModel *wellChosen0 = [self creatCellModel:[BKMain_SimplePicCell class] userInfo:@"0" size:CGSizeMake(SCREENWIDTH, h)];
    
    [wellItemArray addObject:wellChosen0];
    for (NSInteger i = 0; i< jxArray.count; i++) {
        NSDictionary *dictionary = jxArray[i];
        [wellArray addObject:dictionary[@"goodsList"]];
    }
    
    
    for (NSInteger i = 0; i < wellArray.count; i++) {
        NSArray *temp = wellArray[i];
        for (NSInteger j = 0; j < temp.count; j++) {
            BKmain_CellModel *wellChosen = [self creatCellModel:[BKMain_RecommendCell class] userInfo:temp[j] size:[BKMain_RecommendCell calculateSize:temp[j]]];
            [wellItemArray addObject:wellChosen];
        }
        BKMain_SectionModel *section4 = [self createSectionModel:wellItemArray headerHeight:0 footerHeight:10];
        [_dataArray addObject:section4];
    }
    
    NSArray *categoryIconList = data[@"categoryIconList"];
    NSMutableArray *classifyGoods = [NSMutableArray array];
    NSMutableArray *nameArray = [NSMutableArray array];
    for (NSInteger i = 0; i< categoryIconList.count; i++) {
        
        NSDictionary *dictionary = categoryIconList[i];
        [classifyGoods addObject:dictionary[@"goodsList"]];
        [nameArray addObject:dictionary[@"name"]];
    }
    for (NSInteger i = 0; i < nameArray.count; i++) {
        NSMutableArray *goodsList = [NSMutableArray array];
        BKmain_CellModel *classifyHeader = [self creatCellModel:[BKMain_ClassifyTitleCell class] userInfo:categoryIconList[i] size:CGSizeMake(SCREENWIDTH, 40)];
        [goodsList addObject:classifyHeader];
        NSArray *tem = classifyGoods[i];
        for (NSInteger j = 0; j < tem.count; j++) {
            BKmain_CellModel *classifyModel = [self creatCellModel:[BKMain_ClassifyViewCell class] userInfo:tem[j] size:[BKMain_ClassifyViewCell calculateSize:tem[j]]];
            [goodsList addObject:classifyModel];
        }
        BKMain_SectionModel *section5 = [self createSectionModel:goodsList headerHeight:0 footerHeight:10];
        [_dataArray addObject:section5];
        
    }
    
    NSArray *newSalesGoodsArray = [data objectForKey:@"newSalesGoods"];
    if (newSalesGoodsArray != 0) {
        BKmain_CellModel *hotTitleModel = [self creatCellModel:[BKMain_GoodsTitleCell class] userInfo:NewerTitle size:[BKMain_GoodsTitleCell calculateSize:newSalesGoodsArray]];
        BKmain_CellModel *hotModel = [self creatCellModel:[BKMain_thwartwiseGoodsCell class] userInfo:newSalesGoodsArray size:[BKMain_thwartwiseGoodsCell calculateSize:newSalesGoodsArray]];
        BKMain_SectionModel *section2 = [self createSectionModel:@[hotTitleModel,hotModel] headerHeight:0 footerHeight:10];
        [_dataArray addObject:section2];
        
    }
    if (self.index == 1 || self.index == 2) {
        CGFloat h = (SCREENWIDTH < 375) ? (90*SCREENWIDTH/375.f + 10) : (90*SCREENWIDTH/375.f);
        BKmain_CellModel *PicChosen0 = [self creatCellModel:[BKMain_SimplePicCell class] userInfo:[NSString stringWithFormat:@"%ld",(long)self.index] size:CGSizeMake(SCREENWIDTH, h)];
        BKMain_SectionModel *section5 = [self createSectionModel:@[PicChosen0] headerHeight:0 footerHeight:0];
        [_dataArray addObject:section5];
    }
    NSArray *hotSaleGoods = data[@"hotSaleGoods"];
    NSMutableArray *goodsCategory = [NSMutableArray array];
    NSMutableArray *categoryNameArray = [NSMutableArray array];
    for (NSInteger i = 0; i< hotSaleGoods.count; i++) {
        
        NSDictionary *dictionary = hotSaleGoods[i];
        [goodsCategory addObject:dictionary[@"goodsData"]];
        NSDictionary *itemDic = dictionary[@"goodsCategory"];
        [categoryNameArray addObject:itemDic[@"categoryName"]];
    }
    for (NSInteger i = 0; i < categoryNameArray.count; i++) {
        NSMutableArray *goodsList = [NSMutableArray array];
        BKmain_CellModel *classifyHeader = [self creatCellModel:[BKMain_ClassifyTitleCell class] userInfo:[hotSaleGoods[i] objectForKey:@"goodsCategory"] size:CGSizeMake(SCREENWIDTH, 40)];
        [goodsList addObject:classifyHeader];
        NSArray *tem = goodsCategory[i];
        for (NSInteger j = 0; j < tem.count; j++) {
            BKmain_CellModel *classifyModel = [self creatCellModel:[BKMain_ClassifyViewCell class] userInfo:tem[j] size:[BKMain_ClassifyViewCell calculateSize:tem[j]]];
            [goodsList addObject:classifyModel];
        }
        BKMain_SectionModel *section5 = [self createSectionModel:goodsList headerHeight:0 footerHeight:10];
        [_dataArray addObject:section5];
        
    }
    if ([BKMainCommon checkNetWork] == YES) {
        if (self.index == 1 || self.index == 2) {
            BKmain_CellModel *titleModel = [self creatCellModel:[BKMain_TitleCell class] userInfo:@"" size:[BKMain_TitleCell calculateSize:@""]];
            BKMain_SectionModel *section = [self createSectionModel:@[titleModel] headerHeight:0 footerHeight:10];
            [_dataArray addObject:section];
        }
    }
    
    
    for (BKMain_SectionModel *sectionModel in _dataArray) {
        for (BKmain_CellModel *cellModel in sectionModel.cells) {
            [_myCollectionView registerClass:NSClassFromString(cellModel.className) forCellWithReuseIdentifier:cellModel.reuseIdentifier];
        }
    }
    if (_dataArray.count!=0) {
        [_myCollectionView reloadData];
    }
    
    
    if (self.index == 0) {
        [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
    }
    
}

//请求推荐商品
-(void)requestRecommendData{
    NSString *currentPageStr;
    if (_currentPage == -1) {
        currentPageStr = @"";
    }else{
        currentPageStr = [NSString stringWithFormat:@"%ld",(long)_currentPage];
    }
    NSString *type;
    if (self.index == 1) {
        type = @"inland";
    }else{
        type = @"global";
    }
    __weak typeof(self) weakSelf = self;
    
    __strong typeof(weakSelf) strongSelf = weakSelf;
    
    if(strongSelf.exceptionView) {
        [strongSelf.exceptionView dismiss];
        strongSelf.exceptionView = nil;
    }

    NSDictionary *dic_param = [NSDictionary dictionaryWithObjectsAndKeys:type,@"goods_type",currentPageStr,@"pageNo",[BKMainCommon getUserST],@"st", nil];
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"/recommend"] parameters:dic_param success:^(id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                NSDictionary *data_dic = responseObject[@"data"];
                NSString *totalStr = data_dic[@"totalPage"];
                self.totalPage = [totalStr integerValue];
                [self bindRecommendData:data_dic];
                if (self.currentPage == self.totalPage) {
                    
                    
                }else{
                    [self.myCollectionView.mj_footer endRefreshing];
                }
                
            }else{
                [self.myCollectionView.mj_header endRefreshing];
                [self.myCollectionView.mj_footer endRefreshing];
                [HUD showMessage:@"服务器发生错误"];
            }
        }
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        [self.myCollectionView.mj_header endRefreshing];
        [self.myCollectionView.mj_footer endRefreshing];
        [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];;
        [HUD  showMessage:@"数据请求失败"];
    }];
}
-(void)bindRecommendData:(id)data{
    if (!data) {
        return;
    }
    
    if (self.currentPage == 1 && self.index >2) {
        [self.myCollectionView.mj_header endRefreshing];
    }
    NSMutableArray *itemArr = [NSMutableArray array];
//    if (self.index < 3) {
        NSArray *listArray = [data objectForKey:@"list"];
        if (listArray.count != 0) {
            for (int i = 0; i < listArray.count; i++ ) {
                
                    BKmain_CellModel *recommendModel = [self creatCellModel:[BKMain_RecommendAndClassifyCell class] userInfo:listArray[i] size:[BKMain_RecommendAndClassifyCell calculateSize:listArray[i]]];
                    [itemArr addObject:recommendModel];
            }
        }
        BKMain_SectionModel * secModel = [self createSectionModel:itemArr headerHeight:0 footerHeight:0];
        [self.dataArray addObject:secModel];
        for (BKMain_SectionModel *sectionModel in _dataArray) {
            for (BKmain_CellModel *cellModel in sectionModel.cells) {
                [_myCollectionView registerClass:NSClassFromString(cellModel.className) forCellWithReuseIdentifier:cellModel.reuseIdentifier];
            }
        }
        if (_dataArray.count != 0) {
            [self.myCollectionView reloadData];
        }
        
        
        [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
        return;

//    }
//    
//    if ([data isKindOfClass:[NSMutableArray class]]) {
//        for (NSDictionary *itemDic in data) {
//            NSArray *listArray = [itemDic objectForKey:@"list"];
//            
//            if (listArray.count != 0) {
//                for (int i = 0; i < listArray.count; i++ ) {
//                    if (self.goodsShowType == singleLineShowOneGoods) {
//                        BKmain_CellModel *recommendModel = [self creatCellModel:[BKMain_SingleCollectionViewCell class] userInfo:listArray[i] size:[BKMain_SingleCollectionViewCell calculateSize:listArray[i]]];
//                        [itemArr addObject:recommendModel];
//                    }else{
//                        BKmain_CellModel *recommendModel = [self creatCellModel:[BKMain_RecommendAndClassifyCell class] userInfo:listArray[i] size:[BKMain_RecommendAndClassifyCell calculateSize:listArray[i]]];
//                        [itemArr addObject:recommendModel];
//                    }
//                    
//                 }
//             }
//         }
//    }else{
//        NSArray *listArray = [data objectForKey:@"list"];
//        if (listArray.count != 0) {
//            for (int i = 0; i < listArray.count; i++ ) {
//                if (self.goodsShowType == singleLineShowOneGoods) {
//                    BKmain_CellModel *recommendModel = [self creatCellModel:[BKMain_SingleCollectionViewCell class] userInfo:listArray[i] size:[BKMain_SingleCollectionViewCell calculateSize:listArray[i]]];
//                    [itemArr addObject:recommendModel];
//                }else{
//                    BKmain_CellModel *recommendModel = [self creatCellModel:[BKMain_RecommendAndClassifyCell class] userInfo:listArray[i] size:[BKMain_RecommendAndClassifyCell calculateSize:listArray[i]]];
//                    [itemArr addObject:recommendModel];
//                }
//                
//               }
//          }
//    
//    }
//        BKMain_SectionModel * secModel = [self createSectionModel:itemArr headerHeight:0 footerHeight:0];
//        [self.dataArray addObject:secModel];
//        for (BKMain_SectionModel *sectionModel in _dataArray) {
//            for (BKmain_CellModel *cellModel in sectionModel.cells) {
//                [_myCollectionView registerClass:NSClassFromString(cellModel.className) forCellWithReuseIdentifier:cellModel.reuseIdentifier];
//            }
//        }
//        if (_dataArray.count != 0) {
//            [self.myCollectionView reloadData];
//        }
//        
//        
//        [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
//        
    
}

//-(void)only_changeType:(NSNotification *)sender{
//    NSString * type_change = sender.userInfo[@"goodsShowType"];
//    NSString * index = sender.userInfo[@"index"];
//    if (self.index == [index integerValue]){
//        if ([type_change integerValue] == 1) {
//            self.goodsShowType = singleLineShowOneGoods;
//        }else{
//            self.goodsShowType = singleLineShowDoubleGoods;
//        }
//        if (self.classifyData_Array.count != 0) {
//            [self.dataArray removeAllObjects];
//            [self bindRecommendData:self.classifyData_Array];
//        }else{
//            [self requestClassifyData];
//            
//        }
//    }
//    
//        
//
//    
//
//}
//
//-(void)changeType:(NSNotification *)sender{
//    NSString * type_change = sender.userInfo[@"goodsShowType"];
//    NSString * index = sender.userInfo[@"index"];
//    if ([type_change integerValue] == 1) {
//        self.goodsShowType = singleLineShowOneGoods;
//    }else{
//        self.goodsShowType = singleLineShowDoubleGoods;
//    }
//    
//    if (self.index == [index integerValue]) {
//        if (self.classifyData_Array.count != 0) {
//            [self.dataArray removeAllObjects];
//            [self bindRecommendData:self.classifyData_Array];
//        }else{
//            [self requestClassifyData];
//            
//        }
//    }
//    
//
//
//    
//}
//请求分类商品
-(void)requestClassifyData{
    
    __weak typeof(self) weakSelf = self;
    
    __strong typeof(weakSelf) strongSelf = weakSelf;
    
    if(strongSelf.exceptionView) {
        [strongSelf.exceptionView dismiss];
        strongSelf.exceptionView = nil;
    }
    
    
    [BKIndicationView showInView:self.view Point:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
    NSDictionary *dic_param = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",(long)self.currentPage],@"currentPage",@"",@"channelType",self.categoryId,@"categoryId",@"",@"keyWord",@"-1",@"filterTerms",self.order_key,@"order_key",self.sort_name,@"sort_name", nil];
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"/searchGoodsList"] parameters:dic_param success:^(id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                
                [self.myCollectionView.mj_header endRefreshing];
                [self.myCollectionView.mj_footer endRefreshing];
                NSDictionary *data_dic = responseObject[@"data"];
                NSString *totalStr = data_dic[@"totalPage"];
                self.totalPage = [totalStr integerValue];
                if (self.currentPage == self.totalPage) {
                    self.isShowNoData = YES;
                }
                if (self.currentPage == 1 && data_dic.count != 0) {
                    [self.dataArray removeAllObjects];
//                    [self.classifyData_Array removeAllObjects];
                }
//                [self.classifyData_Array addObject:data_dic];
                [self bindRecommendData:data_dic];
                
                [self.myCollectionView.mj_header endRefreshing];
                if (self.currentPage == self.totalPage) {
                    self.myCollectionView.mj_footer = nil;
                    
                }else{
                    [self.myCollectionView.mj_footer endRefreshing];
                }
                if ([self.order_key isEqualToString:@""] && self.currentPage == 1) {
                    BKFirstPageDataModel *dataModel = [BKFirstPageDataModel getCurrentFPData:FPData_thirdType];
                    NSDictionary *dataDic = [self dicWithData:dataModel.FPData_third];
                    NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithDictionary:dataDic];
                    if (resultDic.allKeys.count != 0) {
                        for (NSString *str in resultDic.allKeys) {
                            if ([str isEqualToString:self.categoryId]) {
                                [resultDic removeObjectForKey:self.categoryId];
                                [resultDic setObject:data_dic forKey:self.categoryId];
                            }else{
                                [resultDic setObject:data_dic forKey:self.categoryId];
                            }
                        }
                        
                    }else{
                        [resultDic setObject:data_dic forKey:self.categoryId];
                    }
                    
                    NSData *data = [self returnDataWithDictionary:resultDic];
                    BKFirstPageDataModel *result_dataModel = [BKFirstPageDataModel getCurrentFPData:FPData_thirdType];
                    [result_dataModel.realm beginWriteTransaction];
                    result_dataModel.FPData_third = data;
                    [result_dataModel.realm commitWriteTransaction];
                }
                
                
                
                
                
            }else{
                if (self.currentPage == 1 && self.index >2) {
                    NSData *data = [BKFirstPageDataModel getCurrentFPData:FPData_thirdType].FPData_third;
                    NSDictionary *resultDic = [[self dicWithData:data] objectForKey:self.categoryId];
                    if (resultDic.allKeys != 0) {
                        [self bindRecommendData:resultDic];
                    }else{
                        [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
                        [self setUpErrorUIWith:502];
                    }
                    
                }else{
                    [HUD showMessage:@"服务器发生错误"];
                }
                
                [self.myCollectionView.mj_header endRefreshing];
                [self.myCollectionView.mj_footer endRefreshing];
                
            }
        }
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (error && !weakSelf.exceptionView) {
            [BKIndicationView dismissWithCenter:CGPointMake(ScreenWidth/2, ScreenHeight/2-67)];
            if (self.currentPage == 1 && self.index > 2) {
                NSData *data = [BKFirstPageDataModel getCurrentFPData:FPData_thirdType].FPData_third;
                NSDictionary *resultDic = [[self dicWithData:data] objectForKey:self.categoryId];
                if (resultDic.allKeys != 0) {
                    [self bindRecommendData:resultDic];
                }else{
                    [self setUpErrorUIWith:error.code];
                }

            }else{
                [HUD showMessage:@"数据请求失败"];
            }
            
            [self.myCollectionView.mj_header endRefreshing];
            [self.myCollectionView.mj_footer endRefreshing];
        }
        
    }];
}
-(void)setUpErrorUIWith:(NSInteger)code{
    ExceptionCodeType type = ExceptionCodeTypeNoNetwork;
    if (code == -1009) {
        type = ExceptionCodeTypeNoNetwork;
    }else if (code == -1001){
        type = ExceptionCodeTypeRequestFailed;
    }else if (code == 502 || code == 404){
        type = ExceptionCodeTypeServerError;
    }else{
        type = ExceptionCodeTypeFailedToLoad;
    }
    if (iPhone5 || iPhone4s) {
        self.exceptionView = [ExceptionView exceptionViewWithType:type controller:self];
    }else{
        self.exceptionView = [ExceptionView exceptionViewWithType:type];
    }
    
    ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:type handler:^(ExceptionViewAction *action) {
        [self requestListData];
    }];
    self.exceptionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
    [self.exceptionView addAction:retryAction];
    [self.exceptionView showInView:self.view];
    
}
#pragma mark ------------------跳转详情分类-------------------------
//type:1:分类, 2/3:商品详情, 4:h5, 5:大分类如国内商品, 6:需要传st的h5, 7:话费充值和积分签到
//code:对应type的分类id、商品编号、h5地址、大分类code值[1:国内商品，2：全球购，3：有糖自营]， type7的code[4:充话费, 5:签到]
-(void)pushWithType:(NSString*)type code:(NSString*)code name:(NSString*)name saleTypes:(id)saleTypes{
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    
    id object = [self nextResponder];
    while (![object isKindOfClass:[RootNavigationController class]] && object != nil){
        object = [object nextResponder];
    }
    RootNavigationController *navi = (RootNavigationController*)object;
    
    if([[NSString stringWithFormat:@"%@", type] isEqualToString:@"1"]){
        
        Mediator *mediator = [Mediator sharedInstance];
        UIViewController *classifyVC = [mediator HomeIntorecordPushInformationWithFilterTerms:@"-1" categotyId:code channelType:@"" orderKey:@"" currentPage:0 keyWord:@"" order:@""];
        classifyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:classifyVC animated:YES];
        
    }else if([[NSString stringWithFormat:@"%@", type] isEqualToString:@"2"] || [[NSString stringWithFormat:@"%@", type] isEqualToString:@"3"]) {
        Mediator *mediator = [Mediator sharedInstance];
        UIViewController *detailVC = [mediator BKGD_goodsDetailViewController:code saleTypes:saleTypes];
        detailVC.view.backgroundColor = [UIColor whiteColor];
        [navi pushViewController:detailVC animated:YES];
        
    }else if([[NSString stringWithFormat:@"%@", type] isEqualToString:@"4"]) {
        
        BKMain_WebViewController *h5 =[[BKMain_WebViewController alloc]init];
        h5.webViewTitle = name;
        h5.webViewUrl = code;
        h5.type = type;
        [navi pushViewController:h5 animated:YES];
        
    }else if([[NSString stringWithFormat:@"%@", type] isEqualToString:@"5"]){
        Mediator *mediator = [Mediator sharedInstance];
        UIViewController *classifyVC = [mediator HomeIntorecordPushInformationWithFilterTerms:@"-1" categotyId:@"" channelType:code orderKey:@"" currentPage:0 keyWord:@"" order:@""];
        classifyVC.view.backgroundColor = [UIColor whiteColor];
        classifyVC.hidesBottomBarWhenPushed = YES;
        [navi pushViewController:classifyVC animated:YES];
        
    }else if ([[NSString stringWithFormat:@"%@", type] isEqualToString:@"6"]){
        if (![BKMainCommon islogin]) {
            Mediator *mediator = [Mediator sharedInstance];
            [mediator userGoToLoginFromOrignalController:self finishBlock:^ {
                
            }];
            
        }else{
            
            BKMain_WebViewController *h5 =[[BKMain_WebViewController alloc]init];
            h5.webViewTitle = name;
            h5.webViewUrl = code;
            h5.type = type;
            [navi pushViewController:h5 animated:YES];
            
        }
    }else if ([[NSString stringWithFormat:@"%@", type] isEqualToString:@"7"]){
        
    }
}

-(BKmain_CellModel *)creatCellModel:(Class)cls userInfo:(id)userInfo size:(CGSize)size{
    BKmain_CellModel *model = [[BKmain_CellModel alloc]init];
    model.selectorString = UITableViewCellSelectionStyleNone;
    model.userInfo = userInfo;
    model.size = size;
    model.className = NSStringFromClass(cls);
    return model;
}

-(BKMain_SectionModel*)createSectionModel:(NSArray<BKmain_CellModel*>*)items headerHeight:(CGFloat)headerHeight footerHeight:(CGFloat)footerHeight {
    BKMain_SectionModel *model = [BKMain_SectionModel sectionModelWithTitle:nil cells:items];
    model.headerhHeight = headerHeight;
    model.footerHeight = footerHeight;
    return model;
}
-(NSMutableArray<BKMain_SectionModel *> *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

//-(NSMutableArray *)classifyData_Array{
//    if (!_classifyData_Array) {
//        _classifyData_Array = [[NSMutableArray alloc]init];
//    }
//    return _classifyData_Array;
//}

//字典转data
-(NSData *)returnDataWithDictionary:(NSDictionary *)dict
{
    NSMutableData * data = [[NSMutableData alloc] init];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:dict forKey:@"talkData"];
    [archiver finishEncoding];
    
    return data;
}
-(NSDictionary *)dicWithData:(NSData *)data{
    
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    
    NSDictionary* myDictionary = [unarchiver decodeObjectForKey:@"talkData"];
    
    [unarchiver finishDecoding];
    return myDictionary;
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshFirstPageData" object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"only_changeTypeNotication" object:@"goodsShowType"];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeTypeNotication" object:@"goodsShowType"];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
